import { Tabbar } from 'react-vant';

import {
  Outlet,
  useNavigate,
  useLocation
}  from 'react-router-dom';

import {
  useState,
  useEffect
} from 'react';

import {
  useSelector,
  useDispatch
} from 'react-redux';

import { changeCount, changeIsLoadShopbagCount } from '../store/store';

import axios from 'axios';

function Main() {

  let shopbagCount = useSelector(state => state.publicModule.count);

  let isLoadShopbagCount = useSelector(state => state.publicModule.isLoadShopbagCount);

  let dispatch = useDispatch();

  let navigate = useNavigate();

  let location = useLocation();
  let currentPathname = location.pathname;
  // 

  //定义tabbar数据
  let tabbarData = [
    {
      title: '首页',
      activeIcon: require('../images/home_active.png'),
      inactiveIcon: require('../images/home.png'),
      pathname: '/',
     
    },
    {
      title: '菜单',
      activeIcon: require('../images/menu_active.png'),
      inactiveIcon: require('../images/menu.png'),
      pathname: '/menu'
    },
    {
      title: '购物袋',
      activeIcon: require('../images/shopbag_active.png'),
      inactiveIcon: require('../images/shopbag.png'),
      pathname: '/shopbag',
      badge: shopbagCount > 0 ? shopbagCount : ''
    },
    {
      title: '我的',
      activeIcon: require('../images/my_active.png'),
      inactiveIcon: require('../images/my.png'),
      pathname: '/my'
    },

  ];

  let [activeIndex, setActiveIndex] = useState(0);

  
  //切换tabbar
  let toggleTabbar = index => {
    // 

    //获取当前pathname
    let pathname = tabbarData[index].pathname;

    //跳转页面
    navigate(pathname);

    setActiveIndex(index);
  }

  //如果用户登录, 则获取购物袋商品数量
  let getShopbagCount = () => {
    axios({
      method: 'get',
      url: '/shopcartCount'
    }).then(res => {
      

      if (res.data.code === 700) {
        //未登录
        dispatch(changeCount(0));
        dispatch(changeIsLoadShopbagCount(false));
      } else if (res.data.code === 4000) {
        dispatch(changeCount(res.data.result));
        dispatch(changeIsLoadShopbagCount(true));
      }


    }).catch(err => {
      
    })
  }



  useEffect(() => {

    for (let i = 0; i < tabbarData.length; i++) {
      if (currentPathname === tabbarData[i].pathname) {
        setActiveIndex(i);
        break;
      }
    }

    if (!isLoadShopbagCount) {
      
      getShopbagCount();
    }
    
    

  }, [])

  return (
    <div className="main">

      <div>
        {/* Main页面的二级路由插座 */}
        <Outlet></Outlet>
      </div>

     <Tabbar value={activeIndex} activeColor="#0C34BA" inactiveColor="#646566" onChange={index => {toggleTabbar(index)}}>
      {
        tabbarData.map((item, index) => {
          return (
            <Tabbar.Item key={index} badge={{content: item.badge}} icon={ac => <img src={ac ? item.activeIcon : item.inactiveIcon} />}>{item.title}</Tabbar.Item>
          );
        })
      }
        
      </Tabbar>
    </div>
  );
}

export default Main;